// luanmad added --------------------------- start -----------------------------------------------------------
//------------------------------------------ initialize ------------------------------------------------------
var maxNodeId;
var currentNodeId;
var deleteNodeId ;
var currentNodeName ;
var belongNodeName ;
var currentNodePid ;
var currentNodeUrl ;
var maxSort ;
var as ;
d = new dTree('d', 'dtree');
d = new dTree('d', 'dtree');
d.config.folderLinks = false;
d.config.closeSameLevel = false;
d.add(0, -1, 'Categories', '#', 'aaa', 'frmview', 'images/ajax_dtree/folder.gif', 0, "Categories");


$(document).ready(function()
{
	
	$.ajax({
			url:"treeNodesList.action",
			type:"post",
			data:"",
			dataType:"json",
			success:function(data)
			{
		         //alert(data.treeNodesString);
		         eval(data.treeNodesString);
		         
		         d.delegateAdd = function (id, name)
		         {
		        	 //alert("add now");
		             maxNodeId = d.getMaxNodeId();
		             currentNodeId = id;
		             currentNodeName = d.getCurrentNodeName(id);
		             maxSort = d.getMaxSort();
		             
		             //alert("maxSort:"+maxSort);
		             //alert("currentNodeId:"+currentNodeId);
		             //as = $("div>a");
		             as = $(".thickbox");
		             as.click(showDiv);//display inputText when click 'add link'
		             //return currentNodeId to addOrUpdateNode.jsp when click 'add link'
		             //then it will load all categories in the option
		             $.ajax(
		             {
		                 type:"post",
		                 //url:"addOrUpdateNode.jsp",
		                 url:"jsp/add.jsp",
		                 //data:"action=ADD&currentNodeId=" + currentNodeId + "&catid=" + currentNodeId ,
		                 data:"treeNodes.sort=" + (maxSort + 1) + "&treeNodes.id=" + currentNodeId +"&treeNodes.name="+myFilterEncode(name),
		                 success:function(data)
		                 {
		                     $("#addDiv").html(data);
		                     
		                 }
		             });


		         };


		         // update node
		         d.delegateUpdate = function (id, sort)
		         {
		             currentNodeId = id;
		             currentNodeName = d.getCurrentNodeName(id);
		             currentNodePid = d.getCurrentNodePid(currentNodeId);
		             currentNodeUrl = d.getCurrentNodeUrl(id);
		             //alert(currentNodeUrl);
		             //            alert("pid=" + currentNodePid);
		             as = $(".thickbox");
		             as.click(showDiv);//display inputText when click 'add link'

		             //return currentNodeId to addOrUpdateNode.jsp when click 'add link'
		             //then it will load all categories in the option
		             $.ajax(
		             {
		                 type:"post",
		                 url:"listParentNodes.action",
		                 //data:"action=UPDATE&currentNodeId=" + currentNodePid,
		                 data:"treeNodes.sort="+sort+"&treeNodes.id=" + id + "&treeNodes.name=" + myFilterEncode(currentNodeName) + "&treeNodes.pid=" + currentNodePid+"&treeNodes.url="+currentNodeUrl,
		                 success:function(data)
		                 {
		                     $("#addDiv").html(data);

		                 }
		             });

		         };

		         d.delegateSort = function (sort, id, move)
		         {
		        	 alert("sorting...");
		             currentNodeId = id;
		             currentNodePid = d.getCurrentNodePid(currentNodeId);
		             //currentNodeName = d.getCurrentNodeName(id);

		             $.ajax(
		             {
		                 type:"post",
		                 url:"treeNodesSort.action",
		                 data:"treeNodes.id=" + currentNodeId + "&treeNodes.pid=" + currentNodePid + "&move=" + move + "&treeNodes.sort=" + sort,
		                 success:function(data)
		                 {

//		                    if (data == "SORTSUCCESS")
//		                     {
		                         window.location = "menu.jsp";
		 						 alert(" 移动成功！ ");
//		                     }
//		                     else
//		                     {
//		                    	 alert("移动失败！");
//		                     }
		                     //alert(data);
		                 }

		             });

		         };

		         d.delegateCount = function(id)
		         {
		             currentNodeId = id;
		             //toolTips(id);
		             $(".tooltips").mouseover(toolTips);

		         };

		         d.delegateRemove = function (id)
		         {
		             currentNodeId = id;
//		             alert("delegate remove id = "+currentNodeId);
		             var deleteFlag = confirm('是否删除 ？ ');
		             var countChildren = d.countChildren(currentNodeId);
		             if (deleteFlag)
		             {
		            	 //currentNodeName = d.getCurrentNodeName(id);
		                 //alert(currentNodeName + " has " + countChildren+" children! ");

		                 if (countChildren == 0 && currentNodeId != undefined)
		                 {
                             alert("deleting...");
		                     $.ajax(
		                     {
		                         type:"post",
		                         url:"treeNodesDelete.action?date="+Date.parse(new Date()),
		                         //data:"action=DELETE&currentNodeId=" + currentNodeId,
		                         data:"treeNodes.id=" + currentNodeId,
		                         //contentType:"application/x-www-form-urlencoded",
		                         success:function(data)
		                         {

		                                 d.remove(currentNodeId);
		                                 d.draw();
		                                 //alert(" Deleted success!");
		 								alert(" 删除成功! ");
		                         }
		                     });//.responseText;

		                 }
		                 else
		                 {
		                     //alert("You have too many subcategory,please delete your subcategory first");
		 					alert("此类别有子类别，请先删除子类别。");
		                 }
		             }
		             else
		             {
		                 //alert("Cancel Delete");
		 				alert("删除已取消！");
		             }
		             hideDiv();
		         };
		         
			}
	});
	hideDiv();
	
});

//------------------------------------------- operating ------------------------------------------------------
function nodeOperate_add()
{

    var nodeSort = maxSort + 1;
    var nodeName = $("#catname").val();
    d.add((maxNodeId + 1), currentNodeId, nodeName, '#' + (maxNodeId + 1) , nodeName, 'frmView', 'images/ajax_dtree/folder.gif', (nodeSort), nodeName, '');
    d.draw();
    hideDiv();
}

function nodeOperate_update()
{
    var nodeName = $("#catname").val();
    //    alert("simpleUpdate nodeName=" + nodeName);
    d.update(currentNodeId, currentNodePid, nodeName);
    d.draw();
    hideDiv();
}


//----------------------------------- show div ------------------------------------------------------
function showDiv()
{
    showDiv(event);
}
function showDiv(oEvent)
{

    $("#dtree").css({
       "display":"none"
//        "opacity": "0.5"
    });
    //   var fullScreenWidth =  screen.availWidth;
    $("#addDiv").css(
    {
        "display":"block",
        "left":  '20%',
        "top":50,
        "background" : '#ffffff',
        "opacity": "1"

    });

    if ($("#addDiv").css("display") == "none")
    {
        $("#addDiv").fadeIn("slow");
    }


}

function hideDiv()
{

    $("#addDiv").fadeOut("slow");
    $("#dtree").css({
        "display":"block"
    });

}

// --------------------------------------- filter ------------------------------------------------------
//decode the checkbox title from 'ajaxArrayEdit.jsp' or 'ajszArrayAdd.jsp'
// the follow charstring can not  be decoded (   ! @ # $ & * ( ) = : / ; ? + '    )
function myFilter(originalStr)
{
    var decodeStr =originalStr; //decodeURI(originalStr, "utf-8");//decodeURI(decodeURI(originalStr, "utf-8"), "utf-8");
    //alert("decodeStr="+decodeStr);
    var filterStr = "" ;
    for (var i = 0; i < decodeStr.length; i ++)
    {
        if ("+" == decodeStr.substring(i, i + 1))
        {
            filterStr += " ";
        }
        else
        {
            filterStr += decodeStr.substring(i, i + 1);
        }

    }
    //alert("filterStr = "+filterStr);
    return filterStr;
}


//--------------------------------- tooltips  ------------------------------
function toolTips()
{
    var settings = {//定义属性
        divoffset : 5,
        backgroundImage : "images/ajax_dtree/count.jpg",
        loadImage : "images/ajax_dtree/bmw.jpg1"
    }

    $('body').append("<div id='tooltip'></div>");//create an object
    var tooltip = $('#tooltip');// get the object that its id equals 'tooltip'
    $(this).bind('mouseover', function(e)
    {
        tooltip.html("<img src=" + settings.loadImage + "/>");//load图片
        Mouse(e);//get mouse coordinate
        var href = "/GetProductCountServlet?minutes=" + (new Date()).getMinutes() + "&currentNodeId=" + currentNodeId;//"edit.jsp";//$(this).attr("alt");
        tooltip.css({
            'top':toppos ,//+ settings.divoffset,
            'left':leftpos + settings.divoffset,
            'background':'url(' + settings.backgroundImage + ') no-repeat',
            'position':'absolute',
            'overflow':'hidden',
            'z-index':'999999',
            'padding':'25px',
            'width': '240px',
            'height':'150px'
        }).show();//show object
        $.get(href, function(data)
        {
            var num = data.split(",");
            //tooltip.html("Product Quantity:" + "<font color=red>" + "&nbsp;&nbsp;" + num[1] + "</font>");
			tooltip.html("商品数量:" + "<font color=red>" + "&nbsp;&nbsp;" + num[1] + "</font>");
        });//get data from servlet 'GetProductCount'
    }).bind('mousemove', function(e)
    {//bind the event to the element
        Mouse(e);
        tooltip.css({
            top: toppos ,//+ settings.divoffset,
            left: leftpos + settings.divoffset
        });
    }).bind('mouseout', function()
    {
        tooltip.hide();
    });
}

var Mouse = function(e)
{
    mouse = new MouseEvent(e);
    leftpos = mouse.x;
    toppos = mouse.y;
};

var MouseEvent = function(e)
{
    this.x = e.pageX;
    this.y = e.pageY;
};


function callbackFun(data)
{
	$("#addDiv").html(data);
	alert(data);
}


//the follow charstring can not  be decoded (   ! @ # $ & * ( ) = : / ; ? + '    )
function myFilterDecode(originalStr)
{
    var decodeStr = decodeURI(decodeURI(originalStr, "utf-8"), "utf-8");
    //alert("decodeStr="+decodeStr);
    var filterStr = "" ;
    for (var i = 0; i < decodeStr.length; i ++)
    {
        if ("+" == decodeStr.substring(i, i + 1))
        {
            filterStr += " ";
        }
        else
        {
            filterStr += decodeStr.substring(i, i + 1);
        }

    }
    //alert("filterStr = "+filterStr);
    return filterStr;
}

function myFilterEncode(originalStr)
{
	// encode twice the original tring so that can decode in firefox ,ie and so on
	// if encode once when decodeing  only show the original in ie.
    var encodeString = encodeURI(encodeURI(originalStr,"utf-8"),"utf-8");
    return encodeString;
}

